package game.map 
{
	/**
	 * ...
	 * @author rnk
	 */
	public class Army 
	{
		public var units:Array = [];
		public var heroes:Array = [];
		public var province:Province;
		
		public function Army(province:Province) 
		{
			this.province = province;
		}
		
		public function AddUnit(unit:Unit):void
		{
			if (units.indexOf(unit) >= 0) return;
			units.push(unit);
			if (unit.army)
				unit.army.RemoveUnit(unit);
			unit.army = this;
		}
		
		public function AddHero(hero:Hero):void
		{
			if (heroes.indexOf(hero) >= 0) return;
			heroes.push(hero);
			if (hero.army)
				hero.army.RemoveHero(hero);
			hero.army = this;
		}
		
		public function Join(otherArmy:Army):void
		{
			if (otherArmy == this) return;
			
			for (var i:int = 0; i < otherArmy.units.length; i++)
			{
				var otherUnit:Unit = otherArmy.units[i];
				otherUnit.army = this;
				units.push(otherUnit);
			}
			otherArmy.units = [];
			
			for (var j:int = 0; j < otherArmy.heroes.length; j++)
			{
				var otherHero:Hero = otherArmy.heroes[j];
				otherHero.army = this;
				
			}
			otherArmy.heroes = [];
			
			if (otherArmy.province)
			{
				otherArmy.province.RemoveArmy();
			}
		}
		
		public function RemoveHero(hero:Hero):void
		{
			var idx:int = heroes.indexOf(hero);
			if (idx >= 0) 
			{
				hero.army = null;
				heroes.splice(idx,1);
			}
			
			if (province && IsEmpty())
				province.RemoveArmy();
		}
		
		public function RemoveUnit(unit:Unit):void
		{
			var idx:int = units.indexOf(unit);
			if (idx >= 0) 
			{
				unit.army = null;
				units.splice(idx,1);
			}
			
			if (province && IsEmpty())
				province.RemoveArmy();
		}
		
		public function IsEmpty():Boolean
		{
			return (units.length == 0 && heroes.length == 0);
		}
		
	}

}